package com.hmdp.service.impl;

import java.time.LocalDateTime;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private final RabbitTemplate rabbitTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;


    static { //static 块，初始化static变量
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024 * 1024);


    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
//    @PostConstruct
//    private void init() {
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//    }
//
//    private class VoucherOrderHandler implements Runnable{
//
//        @Override
//        public void run() {
//            while(true){
//                try{
//                    //获取队列中的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //创建订单
//                    createVoucherOrder(voucherOrder);
//                } catch (Exception e){
//                    log.error("处理订单异常",e);
//                }
//            }
//        }
//    }

    /**
     * 基于redission分布式锁，阻塞队列的优惠券秒业务
     * @param voucherId
     * @return
     */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//        //引用lua脚本，校验库存，一人一单资格
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),//key
//                voucherId.toString(), userId.toString() //value
//        );
//        int r = result.intValue();
//        //判断接口是否为0
//        if (r != 0) {
//            //不为0，则返回异常
//            return Result.fail(r == 1?"库存不足":"不能重复下单");
//        }
//        //为0 扣减库存,生成订单，返回订单id
//        //.创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        // 订单id
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//        // 用户id
//        voucherOrder.setUserId(userId);
//        // 代金券id
//        voucherOrder.setVoucherId(voucherId);
//        //讲优惠券信息传入rediss队列中，异步执行，提高效率
//        orderTasks.add(voucherOrder);
//        //获取代理对象
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        return Result.ok(orderId);
//    }

//    @Transactional
//    public void createVoucherOrder(VoucherOrder voucherOrder) {
//        Long userId = voucherOrder.getUserId();
//        Long voucherId = voucherOrder.getVoucherId();
//        //一人一单
//        int count = this.query()
//                .eq("user_id", userId)
//                .eq("voucher_id", voucherId).count();
//        if(count > 0){
//            //用户已经购买
//            log.error("优惠券限购一张");
//        }
////        扣减库存
//        boolean success = seckillVoucherService.update()
//                .setSql("stock= stock - 1")
//                .eq("voucher_id", voucherId)
//                .gt("stock",0)//where id = ？ and stock > 0
//                .update();
//        if (!success) {
//            log.error("库存不足");
//            return;
//        }
//        this.save(voucherOrder);
//    }

    /**
     * 基于redission分布式锁 + rabbitMQ 优惠券秒杀业务
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
//        查询当前优惠券基本信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        查看优惠券是否属于活动内
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("优惠活动还没开始");
        }
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("优惠活动已经结束");
        }
//        查看商品商品库存是否有剩余
        if (voucher.getStock() < 1) {
            return Result.fail("优惠券已经抢完");
        }
        //根据用户id获取锁，某个用户只能下一单
        Long userId = UserHolder.getUser().getId();
//        SimpleRedisLock lock = new SimpleRedisLock("order:"+ userId,stringRedisTemplate);   //基于redis自带的锁
        //获取锁(可重入)，指定锁的名称
        RLock lock = redissonClient.getLock("lock:order:"+userId);   //利用redission的分布式锁
        //尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位
        boolean isLock = lock.tryLock();
        if(!isLock){
            return Result.fail("不允许重复下单");
        }
        try{
            //基于rabbitmq 实现优惠券的相关业务：扣减库存,生成订单
            rabbitTemplate.convertAndSend("voucher.topic","pay.success",voucherId,message -> {
                message.getMessageProperties().setHeader("userId", UserHolder.getUser().getId());
                return message;
            });
            return Result.ok("抢购成功");
        }finally {
            //释放锁
            lock.unlock();
        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId,Long userId) {
            //一人一单
            int count = this.query()
                    .eq("user_id", userId)
                    .eq("voucher_id", voucherId).count();
            if(count > 0){
                //用户已经购买
                return Result.fail("优惠券限购一张");
            }
//        扣减库存
            boolean success = seckillVoucherService.update()
                    .gt("stock",0)//where id = ？ and stock > 0
                .update();
            if (!success) {
                return Result.fail("优惠券已经抢完");
            }
//        创建优惠券订单
            //6.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            // 6.1.订单id
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            // 6.2.用户id
            voucherOrder.setUserId(userId);
            // 6.3.代金券id
            voucherOrder.setVoucherId(voucherId);
            this.save(voucherOrder);
            return Result.ok(orderId);
        }
}
